import { SignInParam } from './auth.types'
import adminService from '../admin/admin.services'
import { NotFound, Unauthorized } from 'http-errors'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import dotenv from 'dotenv'
dotenv.config()

export default class AuthServices {
  static async signIn(signInParam: SignInParam) {
    //验证用户存不存在
    const admin = await adminService.getAdminByUsername(signInParam.username)
    if (!admin) {
      throw new NotFound('用户不存在')
    }
    if (!bcrypt.compareSync(signInParam.password, admin.password)) {
      throw new Unauthorized('密码错误')
    }

    const token = jwt.sign(
      {
        adminId: admin.id,
      },
      process.env.SECRET!,
      { expiresIn: '30d' },
    )
    return {
      token: token,
    }
  }
}
